import { NextResponse, NextRequest } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// 检查用户是否有权限访问项目
async function checkProjectAccess(userId: string, projectId: string) {
  const projectUser = await prisma.projectUser.findUnique({
    where: {
      userId_projectId: {
        userId,
        projectId,
      },
    },
  });
  
  return !!projectUser;
}

// 检查用户是否是项目管理员或所有者
async function checkProjectAdmin(userId: string, projectId: string) {
  const projectUser = await prisma.projectUser.findUnique({
    where: {
      userId_projectId: {
        userId,
        projectId,
      },
    },
  });
  
  return projectUser?.role === 'ADMIN' || projectUser?.role === 'OWNER';
}

// GET /api/projects/[id] - 获取单个项目详情
export async function GET(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const projectId = params.id;

    // 验证用户访问权限
    const hasAccess = await checkProjectAccess(userId, projectId);
    if (!hasAccess) {
      return NextResponse.json({ error: '没有权限访问此项目' }, { status: 403 });
    }

    // 获取项目详情
    const project = await prisma.project.findUnique({
      where: { id: projectId },
      include: {
        tasks: true,
        users: {
          include: {
            user: {
              select: {
                id: true,
                name: true,
                email: true,
                image: true,
              },
            },
          },
        },
      },
    });

    if (!project) {
      return NextResponse.json({ error: '找不到项目' }, { status: 404 });
    }

    // 格式化项目数据
    const completedTasks = project.tasks.filter(task => task.status === 'DONE').length;
    const formattedProject = {
      id: project.id,
      name: project.name,
      description: project.description,
      status: project.tasks.length > 0 
        ? completedTasks === project.tasks.length 
          ? 'completed' 
          : 'in-progress' 
        : 'planning',
      tasks: {
        total: project.tasks.length,
        completed: completedTasks
      },
      createdAt: project.createdAt,
      updatedAt: project.updatedAt,
      members: project.users.map(({ user, role }) => ({
        id: user.id,
        name: user.name,
        email: user.email,
        image: user.image,
        role: role
      }))
    };

    return NextResponse.json(formattedProject);
  } catch (error) {
    console.error('获取项目详情失败:', error);
    return NextResponse.json(
      { error: '获取项目详情时出错' },
      { status: 500 }
    );
  }
}

// PATCH /api/projects/[id] - 更新项目
export async function PATCH(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const projectId = params.id;

    // 验证用户是否为管理员或所有者
    const isAdmin = await checkProjectAdmin(userId, projectId);
    if (!isAdmin) {
      return NextResponse.json({ error: '没有权限更新此项目' }, { status: 403 });
    }

    const body = await request.json();
    const { name, description } = body;

    // 确保项目存在
    const existingProject = await prisma.project.findUnique({
      where: { id: projectId },
    });

    if (!existingProject) {
      return NextResponse.json({ error: '找不到项目' }, { status: 404 });
    }

    // 更新项目
    const updatedProject = await prisma.$transaction(async (tx) => {
      // 更新项目数据
      const project = await tx.project.update({
        where: { id: projectId },
        data: {
          name: name || existingProject.name,
          description: description !== undefined ? description : existingProject.description,
        },
        include: {
          tasks: true,
        },
      });

      // 记录活动
      await tx.activity.create({
        data: {
          userId,
          type: 'project_updated',
          entityId: projectId,
          data: { projectName: project.name }
        }
      });

      return project;
    });

    // 格式化响应数据
    const completedTasks = updatedProject.tasks.filter(task => task.status === 'DONE').length;
    const formattedProject = {
      id: updatedProject.id,
      name: updatedProject.name,
      description: updatedProject.description,
      status: updatedProject.tasks.length > 0 
        ? completedTasks === updatedProject.tasks.length 
          ? 'completed' 
          : 'in-progress' 
        : 'planning',
      tasks: {
        total: updatedProject.tasks.length,
        completed: completedTasks
      }
    };

    return NextResponse.json(formattedProject);
  } catch (error) {
    console.error('更新项目失败:', error);
    return NextResponse.json(
      { error: '更新项目时出错' },
      { status: 500 }
    );
  }
}

// DELETE /api/projects/[id] - 删除项目
export async function DELETE(request: NextRequest, context: { params: { id: string } }) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const params = await context.params;
    const projectId = params.id;

    // 验证用户是否为所有者
    const projectUser = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId,
        },
      },
    });

    if (!projectUser || projectUser.role !== 'OWNER') {
      return NextResponse.json({ error: '只有项目所有者可以删除项目' }, { status: 403 });
    }

    // 删除项目及相关数据
    await prisma.$transaction([
      // 删除项目
      prisma.project.delete({
        where: { id: projectId },
      }),
      // 记录活动
      prisma.activity.create({
        data: {
          userId,
          type: 'project_deleted',
          entityId: projectId,
          data: { projectId }
        }
      })
    ]);

    return NextResponse.json({ message: '项目已删除' });
  } catch (error) {
    console.error('删除项目失败:', error);
    return NextResponse.json(
      { error: '删除项目时出错' },
      { status: 500 }
    );
  }
} 